<template>
  <div class="buy">
    <div v-if="visible">
      <van-sku
        v-model="showBuy"
        hide-stock
        :show-add-cart-btn="false"
        :reset-selected-sku-on-hide="true"
        hide-selected-text
        buy-text="Confirm"
        :sku="sku"
        :goods="goods"
        :initial-sku="initialSku"
        @sku-selected="handleSkuSelected"
        @buy-clicked="onAddCartClicked"
        ref="sku"
        >
        <template #sku-header-price="props">
          <div class="van-sku__goods-price">
            <span class="van-sku__price-symbol">$</span
            ><span class="van-sku__price-num">{{ props.price }}</span>
          </div>
        </template>
        <template #sku-header-origin-price>
          <span class="van-sku__goods-price">
            <span style="text-decoration:line-through">{{originPriceTips[0]}}</span>
            <span>{{originPriceTips[1]}}</span>
          </span>
          <div class="van-sku-header-item">{{ selectedText }}</div>
        </template>
        <template #sku-stepper>
          <div style="display: none"></div>
          <!-- <van-cell title="账号号码" value="1"></van-cell> -->
        </template>
        <template #sku-messages>
          <div style="display: none"></div>
        </template>
      </van-sku>
    </div>
    <!--pay method-->
    <van-popup v-model="showPay" round position="bottom">
      <div class="van-action-sheet__description">Choose a payment method</div>
      <div class="van-action-sheet__content">
        <div class="content">
          <van-radio-group v-model="payWay">
            <li v-for="item in payInfo.payDetailList" :key="item.payMethodId">
              <van-radio :name="item.methodName">
                <div class="content-img-wrapper">
                  <img
                    :src="require(`./images/${item.methodName}.png`)"
                    class="img-icon">
                  <span class="paypal-rate">
                    <label>
                      <span>+ {{item.rate || '0.00'}}% </span> fee
                    </label>
                  </span>
                </div>
              </van-radio>
            </li>
          </van-radio-group>
        </div>
        <div class="total-pannel">
          <div class="total-pannel-list">
            <div class="total-pannel-list-item">
              <div>Subtotal:</div>
              <div>$ {{PayItemDesc.subtotal}}</div>
            </div>
            <div class="total-pannel-list-item">
              <div>Discount:</div>
              <div>- $ {{PayItemDesc.discount || '0.00'}}</div>
            </div>
            <div class="total-pannel-list-item">
              <div>Payment Fee:</div>
              <div>+ $ {{PayItemDesc.paymentFee || '0.00'}}
                  ({{PayItemDesc.rate || '0.00'}}%)</div>
            </div>
          </div>
          <div class="total-pannel-total">
            <div>Total:</div>
            <div>$ {{PayItemDesc.Total || ''}}</div>
          </div>
        </div>
        <div class="van-sku-actions">
          <van-button type="danger" size="large" block
          icon="lock"
          @click="handleConfirmMethod">
            Go to payment</van-button>
        </div>
      </div>
    </van-popup>
    <!--stripe-->
    <van-popup v-model="showStripe" round position="bottom" closeable>
      <div class="van-action-sheet__description">Credit Card Pay</div>
      <div class="van-action-sheet__content">
        <div class="content" v-if="showStripe">
          <!-- Display a payment form -->
          <form id="payment-form">
            <div id="card-element"><!--Stripe.js injects the Card Element--></div>
            <button id="submit">
              <div class="spinner hidden" id="spinner"></div>
              <span id="button-text">Pay now</span>
            </button>
            <p id="card-error" role="alert"></p>
            <p class="result-message hidden">
              Payment succeeded, The system is processing your subscription.
              Please wait patiently for two minutes.
              You will see your subscription details on your subscription page.Go to
              <a href="" target="_blank">My subscription</a> now.
            </p>
          </form>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
/* eslint-disable @typescript-eslint/no-var-requires */
import Vue from 'vue';
import { getOrderConfirm, creatPaymentIntent } from '@/api/home';
import {
  Sku,
  Cell,
  Popup,
  Button,
  RadioGroup,
  Radio,
  Dialog,
} from 'vant';
import { param2Obj } from '@/utils/help';
import { ERROR_OK } from '@/api/config';
import { payClient } from './client';

Vue.use(Sku);
Vue.use(Cell);
Vue.use(Popup);
Vue.use(Button);
Vue.use(RadioGroup);
Vue.use(Radio);
Vue.use(Dialog);

const PIC = require('@/assets/product/nf.jpg');

export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    sku: {
      type: Object,
      require: true,
    },
    params: {
      type: Object,
      require: true,
    },
  },
  data() {
    return {
      showBuy: false,
      goods: {
        picture: PIC,
      },
      initialSku: {
        monthNum: 1,
        screens: 1,
      },
      selectedSkuComb: null,
      showPay: false,
      payInfo: {
        payDetailList: [],
      },
      payWay: '',
      showStripe: false,
    };
  },
  watch: {
    visible(val) {
      if (val) {
        this.showBuy = val;
      }
    },
    showBuy(val) {
      if (!val) {
        this.$emit('update:visible', false);
      }
    },
  },
  computed: {
    originPriceTips() {
      const tips = [];
      if (this.selectedSkuComb) {
        const { discount, originalPrice } = this.selectedSkuComb;
        tips.push((originalPrice / 100).toFixed(2));
        tips.push(`(-${(discount / 100).toFixed(2)}%)`);
      }
      return tips;
    },
    selectedText() {
      return this.$refs.sku ? this.$refs.sku.selectedText.substring(2) : '';
    },
    PayItemDesc() {
      let ret = {};
      const { payDetailList } = this.payInfo;
      const findIndex = payDetailList.findIndex((item) => item.methodName === this.payWay);
      if (findIndex > -1) {
        ret = { ...payDetailList[findIndex] };
      }
      return ret;
    },
  },
  methods: {
    handleSkuSelected({ selectedSkuComb }) {
      this.selectedSkuComb = selectedSkuComb;
    },
    onAddCartClicked(skuData) {
      const { id } = skuData.selectedSkuComb;
      const params = {
        carSeatId: '',
        isRenewalBill: '',
        productId: '',
        productNum: 1,
        ticketNo: '',
      };
      Object.assign(params, this.params, {
        productId: id,
      });
      const orderJsonStr = JSON.stringify({ orderItemVOList: [params] });
      const { sid } = param2Obj(window.location.search);
      getOrderConfirm({ orderJsonStr, sid }).then((res) => {
        if (res.code === ERROR_OK) {
          this.payInfo = res.data || {};
          const { payDetailList } = res.data || {};
          if (payDetailList.length > 0) {
            this.payWay = payDetailList[0].methodName;
          }
          this.showBuy = false;
          this.showPay = true;
        }
      });
    },
    handleConfirmMethod() {
      if (this.payWay === 'aliexpress') {
        window.open(this.PayItemDesc.link);
        setTimeout(() => {
          Dialog.alert({
            message: ' Was the payment successful?',
            confirmButtonText: 'Confirm',
            showCancelButton: true,
            cancelButtonText: 'Cancel',
          }).then(() => {
            this.$router.push({ path: '/paysuccess' });
          }).catch();
        }, 1000);
      } else {
        creatPaymentIntent({ orderId: this.payInfo.orderId }).then((res) => {
          if (res.code === ERROR_OK) {
            const { clientPK, clientSecret } = res.data;
            this.showStripe = true;
            this.$nextTick(() => {
              payClient({ clientPK, clientSecret });
            });
          }
        });
      }
    },
  },
};
</script>

<style scoped lang="scss">
@media screen and (min-width: 800px) {
  .buy .van-popup--bottom.van-popup--round {
    border-radius:20px
  }
}

@media screen and (min-width: 800px) {
  .buy .van-popup--bottom {
    bottom:18%;
    width: 500px;
    left: 50%;
    margin-left: -250px
  }
}
.van-action-sheet__description {
  position: relative;
  -webkit-flex-shrink: 0;
  flex-shrink: 0;
  padding: 20px 16px;
  color: #969799;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
}
.van-action-sheet__content {
  flex: 1 auto;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  .content {
    padding: 16px;
    font-weight: 700;
    max-height: 35vh;
    overflow-y: auto;
    ::v-deep .van-radio__label {
      width: 100%;
    }
    li {
    margin-bottom: 20px;
    list-style: none;
    .content-img-wrapper {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .img-icon {
        max-height: 30px;
        max-width: 80%;
      }
      .paypal-rate {
        font-weight: 400;
        font-size: 15px;
        width: 100%;
        text-align: right;
        color: #8989c2;
        padding-right: 5px;
      }
    }
  }
  }
  .total-pannel {
    padding: 0 16px;
    .total-pannel-list {
      padding: 8px 0;
      font-size: 15px;
      border: 1px solid #ebedf0;
      border-radius: 4px;
      .total-pannel-list-item {
        display: flex;
        justify-content: space-between;
        padding: 2px 20px;
      }
    }
    .total-pannel-total {
      margin-top: 8px;
      display: flex;
      justify-content: space-between;
      padding: 2px 15px;
      font-weight: 1000;
      font-size: 18px;
    }
  }
  .van-sku-actions {
    display: flex;
    -webkit-flex-shrink: 0;
    flex-shrink: 0;
    padding: 8px 16px;
  }
  .content-img-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
// pay style
* {
  box-sizing: border-box;
}
body {
  font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  font-size: 16px;
  -webkit-font-smoothing: antialiased;
  display: flex;
  justify-content: center;
  align-content: center;
  height: 100vh;
  width: 100vw;
}
form {
  width: 100%;
  align-self: center;
  border-radius: 7px;
}
input {
  border-radius: 6px;
  margin-bottom: 6px;
  padding: 12px;
  border: 1px solid rgba(50, 50, 93, 0.1);
  height: 44px;
  font-size: 16px;
  width: 100%;
  background: white;
}
.result-message {
  line-height: 22px;
  font-size: 16px;
}
.result-message a {
  color: rgb(89, 111, 214);
  font-weight: 600;
  text-decoration: none;
}
.hidden {
  display: none;
}
#card-error {
  color: rgb(105, 115, 134);
  text-align: left;
  font-size: 13px;
  line-height: 17px;
  margin-top: 12px;
}
#card-element {
  border-radius: 4px 4px 0 0 ;
  padding: 12px;
  border: 1px solid rgba(50, 50, 93, 0.1);
  height: 44px;
  width: 100%;
  background: white;
}
#payment-request-button {
  margin-bottom: 32px;
}
/* Buttons and links */
button {
  background: #5469d4;
  color: #ffffff;
  font-family: Arial, sans-serif;
  border-radius: 0 0 4px 4px;
  border: 0;
  padding: 12px 16px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  display: block;
  transition: all 0.2s ease;
  box-shadow: 0px 4px 5.5px 0px rgba(0, 0, 0, 0.07);
  width: 100%;
}
button:hover {
  filter: contrast(115%);
}
button:disabled {
  opacity: 0.5;
  cursor: default;
}
/* spinner/processing state, errors */
.spinner,
.spinner:before,
.spinner:after {
  border-radius: 50%;
}
.spinner {
  color: #ffffff;
  font-size: 22px;
  text-indent: -99999px;
  margin: 0px auto;
  position: relative;
  width: 20px;
  height: 20px;
  box-shadow: inset 0 0 0 2px;
  -webkit-transform: translateZ(0);
  -ms-transform: translateZ(0);
  transform: translateZ(0);
}
.spinner:before,
.spinner:after {
  position: absolute;
  content: "";
}
.spinner:before {
  width: 10.4px;
  height: 20.4px;
  background: #5469d4;
  border-radius: 20.4px 0 0 20.4px;
  top: -0.2px;
  left: -0.2px;
  -webkit-transform-origin: 10.4px 10.2px;
  transform-origin: 10.4px 10.2px;
  -webkit-animation: loading 2s infinite ease 1.5s;
  animation: loading 2s infinite ease 1.5s;
}
.spinner:after {
  width: 10.4px;
  height: 10.2px;
  background: #5469d4;
  border-radius: 0 10.2px 10.2px 0;
  top: -0.1px;
  left: 10.2px;
  -webkit-transform-origin: 0px 10.2px;
  transform-origin: 0px 10.2px;
  -webkit-animation: loading 2s infinite ease;
  animation: loading 2s infinite ease;
}
@-webkit-keyframes loading {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
@keyframes loading {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
@media only screen and (max-width: 600px) {
  form {
    width: 100%;
  }
}
</style>
